package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Role;
import cn.kgc.vue.entity.RolePers;
import cn.kgc.vue.entity.UserRole;
import cn.kgc.vue.mapper.PermissionMapper;
import cn.kgc.vue.mapper.RoleMapper;
import cn.kgc.vue.mapper.RolePersMapper;
import cn.kgc.vue.mapper.UserRoleMapper;
import cn.kgc.vue.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-04-11 10:43:41
*/
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePersMapper rolePersMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult rolePage(QueryCondition<Role> queryCondition) {

        Page<Role> rolePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        String roleCh = queryCondition.getSearchParams().getRoleCh();
        String roleEn = queryCondition.getSearchParams().getRoleEn();

        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        lambda.eq(StringUtils.isNotBlank(roleCh),Role::getRoleCh,roleCh)
                .eq(StringUtils.isNotBlank(roleEn),Role::getRoleEn,roleEn)
                .orderByDesc(Role::getCreateTime);

        baseMapper.selectPage(rolePage,lambda);

        return ResponseResult.success()
                .data("total",rolePage.getTotal())
                .data("tableData",rolePage.getRecords());
    }

    @Override
    public ResponseResult delete(Integer id) {

        //  1.根据角色id  查询sys_user_role
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId,id);

        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        if (ObjectUtils.isNotNull(userRoles)){
            return  ResponseResult.fail().message("角色被占用");
        }
        // 2.删除角色信息
        baseMapper.deleteById(id);

        // 3. 删除  sys_role_pers
        LambdaQueryWrapper<RolePers> lambda1 = new QueryWrapper<RolePers>().lambda();
        lambda1.eq(RolePers::getRoleId,id);
        rolePersMapper.delete(lambda1);

        return ResponseResult.success().message("删除成功");
    }

    @Override
    public ResponseResult roleAuth(Integer id) {

        // 根据id   sys_role_pers   pid
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId,id);
        List<Integer> pIds = rolePersMapper.selectList(lambda).stream().map(rp -> rp.getPerId())
                .collect(Collectors.toList());

        List<Integer> collect = new ArrayList<>();

        // 根据pids  查询所有的权限信息   过滤  isMenu=2
        if (ObjectUtils.isNotNull(pIds)){
            collect = permissionMapper.selectBatchIds(pIds).stream()
                    .filter(permission -> permission.getIsMenu() == 2)
                    .map(permission -> permission.getId())
                    .collect(Collectors.toList());
        }

        return ResponseResult.success().data("authIds",collect);
    }

    @Override
    public ResponseResult addRoleAuth(Map<String, Object> roleAuth) {

        // 1.根据角色id  删除角色的权限   sys_role_permission
        Integer roleId = (Integer) roleAuth.get("roleId");
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId,roleId);
        rolePersMapper.delete(lambda);


        // 2.遍历角色的最新权限id  添加权限到  sys_role_permission
        List<Integer> ids = (List<Integer>) roleAuth.get("ids");
        ids.forEach(pid->{
            RolePers rolePers = new RolePers(roleId, pid);
            rolePersMapper.insert(rolePers);
        });


        return ResponseResult.success().message("授权成功");
    }
}




